package com.yt.sys.server.api.cms;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yt.common.constant.Result;
import com.yt.sys.models.bo.SysAdminBO;
import com.yt.sys.models.dto.SysAdminDTO;
import com.yt.sys.models.entity.SysAdmin;
import com.yt.sys.models.service.ISysAdminService;
import com.yt.common.utils.Md5Utils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/cms/sys/admin")
@Api(tags = "系统管理-管理员管理")
public class SysAdminController {

    @Autowired
    private ISysAdminService sysAdminService;

    @GetMapping("/list")
    @ApiOperation("管理员列表")
    public Result<List<SysAdmin>> list() {
        QueryWrapper<SysAdmin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete", 0);
        queryWrapper.orderByDesc("create_time");
        List<SysAdmin> list = sysAdminService.list(queryWrapper);
        return Result.success(list);
    }

    @GetMapping("/page")
    @ApiOperation("管理员分页列表")
    public Result<Page<SysAdmin>> page(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String realName,
            @RequestParam(required = false) String phone,
            @RequestParam(required = false) Integer status) {
        Page<SysAdmin> page = new Page<>(pageNum, pageSize);
        QueryWrapper<SysAdmin> queryWrapper = new QueryWrapper<>();
        
        // 添加搜索条件
        if (username != null && !username.isEmpty()) {
            queryWrapper.like("username", username);
        }
        if (realName != null && !realName.isEmpty()) {
            queryWrapper.like("real_name", realName);
        }
        if (phone != null && !phone.isEmpty()) {
            queryWrapper.like("phone", phone);
        }
        if (status != null) {
            queryWrapper.eq("status", status);
        }
        
        // 移除手动添加的 is_delete 条件，因为 MyBatis-Plus 会自动处理逻辑删除字段
        queryWrapper.orderByDesc("create_time");
        Page<SysAdmin> result = sysAdminService.page(page, queryWrapper);
        // 清除密码信息
        result.setRecords(result.getRecords().stream().map(admin -> {
            admin.setPassword(null);
            return admin;
        }).collect(Collectors.toList()));
        return Result.success(result);
    }

    @GetMapping("/{id}")
    @ApiOperation("根据ID获取管理员信息")
    public Result<SysAdmin> getById(@PathVariable Integer id) {
        SysAdmin admin = sysAdminService.getById(id);
        if (admin == null || admin.getIsDelete() == 1) {
            return Result.fail("管理员不存在");
        }
        admin.setPassword(null); // 不返回密码信息
        return Result.success(admin);
    }

    @PostMapping
    @ApiOperation("新增管理员")
    public Result<String> add(@Valid @RequestBody SysAdminDTO sysAdminDTO) {
        // 检查用户名是否已存在
        QueryWrapper<SysAdmin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", sysAdminDTO.getUsername());
        queryWrapper.eq("is_delete", 0);
        if (sysAdminService.count(queryWrapper) > 0) {
            return Result.fail("用户名已存在");
        }

        SysAdmin admin = new SysAdmin();
        BeanUtils.copyProperties(sysAdminDTO, admin);
        // 密码加密
        admin.setPassword(Md5Utils.MD5Encode(sysAdminDTO.getPassword()));
        admin.setIsDelete(0);
        boolean result = sysAdminService.save(admin);
        if (result) {
            return Result.success("新增成功");
        } else {
            return Result.fail("新增失败");
        }
    }

    @PutMapping
    @ApiOperation("修改管理员")
    public Result<String> update(@Valid @RequestBody SysAdminDTO sysAdminDTO) {
        if (sysAdminDTO.getAdminId() == null) {
            return Result.fail("管理员ID不能为空");
        }

        SysAdmin admin = sysAdminService.getById(sysAdminDTO.getAdminId());
        if (admin == null || admin.getIsDelete() == 1) {
            return Result.fail("管理员不存在");
        }

        // 检查用户名是否被其他人使用
        QueryWrapper<SysAdmin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", sysAdminDTO.getUsername());
        queryWrapper.eq("is_delete", 0);
        queryWrapper.ne("admin_id", sysAdminDTO.getAdminId());
        if (sysAdminService.count(queryWrapper) > 0) {
            return Result.fail("用户名已存在");
        }

        BeanUtils.copyProperties(sysAdminDTO, admin);
        // 如果密码不为空，则更新密码
        if (sysAdminDTO.getPassword() != null && !sysAdminDTO.getPassword().isEmpty()) {
            admin.setPassword(Md5Utils.MD5Encode(sysAdminDTO.getPassword()));
        }
        boolean result = sysAdminService.updateById(admin);
        if (result) {
            return Result.success("修改成功");
        } else {
            return Result.fail("修改失败");
        }
    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除管理员")
    public Result<String> delete(@PathVariable Integer id) {
        SysAdmin admin = sysAdminService.getById(id);
        if (admin == null || admin.getIsDelete() == 1) {
            return Result.fail("管理员不存在");
        }

        // 使用 MyBatis-Plus 的逻辑删除功能
        boolean result = sysAdminService.removeById(id);
        if (result) {
            return Result.success("删除成功");
        } else {
            return Result.fail("删除失败");
        }
    }

}